<template>
  <div class="container">
    <div>
      <el-row :gutter="26">
        <el-col :span="5">
          <el-form ref="form" :model="form">
            <el-form-item label="司机姓名：">
              <el-input v-model="select.name" placeholder="请输入司机姓名" style="width:150px;"></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-form ref="form" :model="form">
            <el-form-item label="驾照类型：">
              <el-select v-model="form.statusValue" placeholder="请选择驾照类型">
                <el-option
                  v-for="(item,index) in form.statusList"
                  :value="item.label"
                  :label="item.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <!-- <el-col :span="9">
          <el-form ref="form" :model="form">
            <el-form-item label="日期：" :label-width="labelwidth">
              <el-date-picker
                v-model="value2"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="mini"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-form>
        </el-col> -->

        <!-- <el-col :span="6" v-if="form.timeTypeValue === '0'">
          <el-form ref="form" :model="form">
            <el-form-item label="结束日期：" :label-width="labelwidth">
              <el-date-picker
                v-model="form.endDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-form>
        </el-col>-->
        <el-col :span="6">
          <el-form ref="form" :model="form" style="float:left">
            <el-form-item>
              <el-button size="mini" type="primary" @click="screeningData">查 询</el-button>
              <el-button size="mini" type="success" @click="handleAdd">新 增</el-button>
              <!-- <el-button size="mini" type="success" @click="exportExcel">删 除</el-button> -->
            </el-form-item>
            <!-- <el-form-item>
              <el-button size="mini" type="success" @click="exportExcel">批量导入</el-button>
              <el-button size="mini" type="success" @click="exportExcel">批量导出</el-button>
            </el-form-item> -->
          </el-form>
        </el-col>
      </el-row>
    </div>
    <el-table highlight-current-row :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)">
      <el-table-column  prop="ID" label="司机姓名" align="center" width="120"></el-table-column>
      <el-table-column  prop="Dw" label="电话号码" align="center" width="150"></el-table-column>
      <el-table-column  prop="Cph" label="生日" align="center" width="120"></el-table-column>
      <el-table-column  prop="Model" label="入司时间" align="center" width="120"></el-table-column>
      <el-table-column  prop="Person" label="驾龄" align="center" width="120"></el-table-column>
      <el-table-column  prop="Buytime" label="驾驶证号" align="center" width="120"></el-table-column>
      <el-table-column  prop="Explain" label="驾照类型" align="center" width="150"></el-table-column>
      <el-table-column  prop="Explain" label="准驾车型" align="center" width="120"></el-table-column>
      <el-table-column  prop="Explain" label="血型" align="center" width="120"></el-table-column>
      <el-table-column  prop="Explain" label="驾照生效时间" align="center" width="120"></el-table-column>
      <el-table-column  prop="Explain" label="时效" align="center" width="120"></el-table-column>
      <el-table-column  prop="Explain" label="性别" align="center" width="120"></el-table-column>
      <el-table-column  prop="Explain" label="司机照片" align="center" width="120"></el-table-column>
      <el-table-column  prop="Explain" label="车本照片" align="center" width="120"></el-table-column>
      <el-table-column label="操作" width="180" align="center" >
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            @click="handleDelete(scope.$index, scope.row)"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
    <!-- 图片放大 -->
    <el-dialog
      title="图片展示"
      :visible.sync="showBigDialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-image
        style="width: 100%; height: 100%"
        :src="srcBig"
      ></el-image>
    </el-dialog>
    <!-- 弹出框 -->
    <el-dialog
      :title="addDialogTitle"
      :visible.sync="isVisibleEdit"
      width="50%"
    >
      <el-form
        ref="form" 
        :model="form"
        label-width="100px"
        class="flex"
      >
        <el-form-item label="车牌照号：" class="wid50">
          <el-input
            v-model="form.CPH"
            placeholder="请输入车牌照号"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="车辆类型：" class="wid50">
          <el-input
            v-model="form.INSPECTPERSON"
            placeholder="请输入车辆类型"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="资产单位：" class="wid50">
          <el-input
            v-model="form.DW"
            placeholder="请输入资产单位"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="机动车保管人：" class="wid50">
          <el-input
            v-model="form.PERSON"
            placeholder="请输入机动车保管人"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="机动车所有人：" class="wid50">
          <el-input
            v-model="form.VOWNER"
            placeholder="请输入机动车所有人"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="购置日期：" :label-width="labelwidth">
          <el-date-picker
            v-model="form.BUYTIME"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="使用部门名称：" class="wid50">
          <el-input
            v-model="form.USEDEPTNAME"
            placeholder="请输入使用部门名称"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="使用部门ID：" class="wid50">
          <el-input
            v-model="form.USEDEPTID"
            placeholder="请输入使用部门ID"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="说明：" class="wid50">
          <el-input
            v-model="form.EXPLAIN"
            placeholder="请输入说明"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌型号：" class="wid50">
          <el-input
            v-model="form.BRAND"
            placeholder="请输入品牌型号"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="车架号：" class="wid50">
          <el-input
            v-model="form.Vin"
            placeholder="请输入车架号"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="发动机号：" class="wid50">
          <el-input
            v-model="form.ENGINENUM"
            placeholder="请输入发动机号"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="排气量：" class="wid50">
          <el-input
            v-model="form.DISCHARGERATE"
            placeholder="请输入排气量"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="使用状态：" class="wid50">
          <el-input
            v-model="form.VCONDITION"
            placeholder="请输入使用状态"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
                <el-form-item label="组织级别：" class="wid50">
          <el-select
            v-model="form.CTYPE"
            placeholder="请选择"
            @change="changClient"
          >
            <el-option
              v-for="item in rolelevel"
              :key="item.rolelevelindex"
              :label="item.roleleveltitle"
              :value="item.rolelevelindex"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组织机构：" class="wid50">
          <el-select
            v-model="form.CLIENT_NO_select"
            value-key="id"
            placeholder="请选择"
            @change="$forceUpdate()"
          >
            <el-option
              v-for="item in selectClientInfoList"
              :key="item.CLIENT_NO"
              :label="item.CLIENT_NAME"
              date-name="item.CLIENT_NAME"
              :value="item.CLIENT_NO"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="购置价格：" class="wid50">
          <el-input
            v-model="form.PRICE"
            placeholder="请输入购置价格"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="绑定司机：" class="wid50">
          <el-input
            v-model="form.USE"
            placeholder="请输入绑定司机"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="车辆图片：">
          <input type="file" ref="file" />
        </el-form-item>
        <el-form-item label="车本图片：">
          <input type="file" ref="file" />
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import '@/assets/css/common.css'

import export2Excel from '@/utils/exportExcel/index.js'
import OSS from 'ali-oss';



export default {
  data () {

    return {
      currentPage: 1, //初始页
      pageSize: 10,    //    每页的数据
      originalData: [],
      tableData: [],
      select: {
        name: ''
      },
      isVisibleEdit: false,
      rolelevel: [{
        roleleveltitle: '公司',
        rolelevelindex: '-1'
      }, {
        roleleveltitle: '项目',
        rolelevelindex: '0'
      }, {
        roleleveltitle: '机扫',
        rolelevelindex: '1'
      }, {
        roleleveltitle: '垃圾',
        rolelevelindex: '2'
      }, {
        roleleveltitle: '人工',
        rolelevelindex: '3'
      }, {
        roleleveltitle: '公厕维保',
        rolelevelindex: '4'
      }],
      form: {
        DW: "",
        CPH: "",
        MODEL: "",
        PERSON: "",
        BUYTIME: "",
        EXPLAIN: "",
        USEDEPTNAME: "",
        USEDEPTID: "",
        VOWNER: "",
        BRAND: "",
        VIN: "",
        ENGINENUM: "",
        DISCHARGERATE: "",
        VCONDITION: "",
        PRICE: "",
        CLIENT_NO: [],
        USE: "",
      },
      showBigDialogVisible: false,
      srcBig: '',
      //图片上传
      fileList: [],
      VehicleUrl: '', //存上传后的车辆图片url
      CBPicUrl: '', //存上传后的车本图片url
      dataObj: {
          region: 'oss-cn-beijing',//我的存储是北京，可根据具体配置自行修改
          accessKeyId: 'LTAISI12uxTRFccz',
          accessKeySecret: 'cQAvLIZ9JizT5RXRNPBVcXfg3iURD8',
          bucket: 'photo-srw-hb2',
      }, //存签名信息
      baseAli:'oss-cn-beijing.aliyuncs.com',
    } 
  },
  created () {
  },
  mounted () {
    this.getlistdata()
    
    // this.screeningData()
  },
  methods: {
    //获取车牌列表
    async getlistdata () {
      var url = '/DataListCompany/GetCarInformationListApi?ClientNo=' + localStorage.getItem('CLIENT_NO')
      const { data } = await this.$Http.get(url)
      this.originalData = data
      this.screeningData()
      // this.tableData = data
    },
    // 导出Excel
    exportExcel () {
      // export2Excel(this.sjcc.tHeader, this.sjcc.filterVal, this.tableData, this.sjcc.excelName)
    },
    // 打开新增窗口
    handleAdd () {
      this.addDialogTitle = '新增车辆基础信息'
      //清空编辑框
      this.form = {
        DW: "",
        CPH: "",
        MODEL: "",
        PERSON: "",
        BUYTIME: "",
        EXPLAIN: "",
        USEDEPTNAME: "",
        USEDEPTID: "",
        VOWNER: "",
        BRAND: "",
        VIN: "",
        ENGINENUM: "",
        DISCHARGERATE: "",
        VCONDITION: "",
        PRICE: "",
        CLIENT_NO: [],
        USE: "",
        VehiclePicPath: "",
        CBPicPath: ""
      }
      //展示窗口
      this.isVisibleEdit = true;
      // this.idEdit = false;
    },
    // 打开编辑窗口
    handleEdit (index, row) {
      this.form = row;
      this.addDialogTitle = '编辑车辆基础信息'
      this.isVisibleEdit = true;
    },
    // 点击保存，判断是新增还是编辑操作
    handleSubmit () {
      if (this.addDialogTitle == '新增车辆基础信息') {
        this.saveAdd()
      } else {
        this.saveEdit()
      }
    },
    // 新增保存
    async saveAdd(){
      Promise.all([this.afterRead1(this.$refs.file.files[0]),this.afterRead2(this.$refs.file.files[0])]).then(() => {
            // console.log(this.addform);
            this.$axios({
                url:'CarService/AddCarInformationInfo',
                method: 'post',
                data:{
                     DW: this.form.DW,
                     CPH: this.form.CPH,
                     MODEL: this.form.MODEL,
                     PERSON: this.form.PERSON,
                     BUYTIME: this.form.BUYTIME,
                     EXPLAIN: this.form.EXPLAIN,
                     USEDEPTNAME: this.form.USEDEPTNAME,
                     USEDEPTID: this.form.USEDEPTID,
                     VOWNER: this.form.VOWNER,
                     BRAND: this.form.BRAND,
                     VIN: this.form.VIN,
                     ENGINENUM: this.form.ENGINENUM,
                     DISCHARGERATE: this.form.DISCHARGERATE,
                     VCONDITION: this.form.VCONDITION,
                     PRICE: this.form.PRICE,
                     CLIENT_NO: this.form.CLIENT_NAME,
                     USE: this.form.USE,
                     VehiclePicPath: this.VehicleUrl,
                     CBPicPath: this.CBPicUrl

                },
                
            }).then((res)=>{
              console.log(this.data)
                console.log(res)
                if(res.data.IsSucess){
                    this.$message.success('新增成功');
                    this.isVisibleEdit =false
                    this.getdata()
                }else{
                    this.$message.error('新增失败');
                }
            })
          })
        },
    // 保存编辑
    async saveEdit(){
      Promise.all([this.afterRead1(this.$refs.file.files[0]),this.afterRead2(this.$refs.file.files[0])]).then(() => {
        let clientNo = ''
        let clientName = ''
        if (this.form.CLIENT_NO_select === this.form.USERNAME) {
          //未做选择修改
          clientNo = this.form.CLIENT_NO
          clientName = this.form.USERNAME
        } else {
          clientNo = this.form.CLIENT_NO_select
          clientName = this.selectClientInfoList.find(val => val.CLIENT_NO == this.form.CLIENT_NO_select).CLIENT_NAME
        }
            // console.log(this.addform);
            this.$axios({
                url:'CarService/UpdataCarInformationInfo',
                method: 'post',
                data:{
                     DW: this.form.DW,
                     CPH: this.form.CPH,
                     MODEL: this.form.MODEL,
                     PERSON: this.form.PERSON,
                     BUYTIME: this.form.BUYTIME,
                     EXPLAIN: this.form.EXPLAIN,
                     USEDEPTNAME: this.form.USEDEPTNAME,
                     USEDEPTID: this.form.USEDEPTID,
                     VOWNER: this.form.VOWNER,
                     BRAND: this.form.BRAND,
                     VIN: this.form.VIN,
                     ENGINENUM: this.form.ENGINENUM,
                     DISCHARGERATE: this.form.DISCHARGERATE,
                     VCONDITION: this.form.VCONDITION,
                     PRICE: this.form.PRICE,
                     CLIENT_NAME: clientName,
                     USE: this.form.USE,
                     VehiclePicPath: this.VehicleUrl,
                     zCBPicPath: this.CBPicUrl

                },
                
            }).then((res)=>{
              console.log(this.data)
                console.log(res)
                if(res.data.IsSucess){
                    this.$message.success('编辑成功');
                    this.isVisibleEdit =false
                    this.getdata()
                }else{
                    this.$message.error('编辑失败');
                }
            })
          })
        },
    async saveEdit1 () {
      let clientNo = ''
      let clientName = ''
      if (this.form.CLIENT_NO_select === this.form.USERNAME) {
        //未做选择修改
        clientNo = this.form.CLIENT_NO
        clientName = this.form.USERNAME
      } else {
        clientNo = this.form.CLIENT_NO_select
        clientName = this.selectClientInfoList.find(val => val.CLIENT_NO == this.form.CLIENT_NO_select).CLIENT_NAME
      }
      console.log(this.form)
      const params = {
        DW: this.form.DW,
        CPH: this.form.CPH,
        MODEL: this.form.MODEL,
        PERSON: this.form.PERSON,
        BUYTIME: this.form.BUYTIME,
        EXPLAIN: this.form.EXPLAIN,
        USEDEPTNAME: this.form.USEDEPTNAME,
        USEDEPTID: this.form.USEDEPTID,
        VOWNER: this.form.VOWNER,
        BRAND: this.form.BRAND,
        VIN: this.form.VIN,
        ENGINENUM: this.form.ENGINENUM,
        DISCHARGERATE: this.form.DISCHARGERATE,
        VCONDITION: this.form.VCONDITION,
        PRICE: this.form.PRICE,
        CLIENT_NAME: this.form.clientName,
        USE: this.form.USE,
        VehiclePicPath: this.VehicleUrl,
        zCBPicPath: this.CBPicUrl
      }
      console.log('编辑车辆基础信息参数：')
      console.log(params)
      const { data } = await this.$Http.get('CarService/UpdataCarInformationInfo', { params })
      if (data.IsSucess) {
        this.$message.success('编辑成功')
        this.isVisibleEdit = false
        this.getRoleList()
      }
    },
      // 删除车辆信息
      async handleDelete (index, row) {
        const confirmResult = await this.$confirm('确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult == 'confirm') {
          const params = {
            ID: row.ID,
          }
          const { data } = await this.$Http.get('CarService/DeleteCarInformationInfo', { params })
          if (data.IsSucess) {
            this.$message.success('删除成功')
            this.isVisibleEdit = false
            this.getlistdata()
          }else {
            this.$message.error('删除失败');
          }
        }else{
          this.$message.info('取消删除')
          this.isVisibleEdit = false
        }
      },
    // 模糊查询
    screeningData () {
      this.currentPage = 1;
      this.tableData = this.originalData
      if (this.select.name) this.tableData = this.tableData.filter(item => item.CPH.includes(this.select.name))
      console.log(this.select.name)
    },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
      // console.log(this.currentPage)
      // this.$set(this.query, 'pageIndex', val);
      // this.getData();
    },
    handleSizeChange (size) {
      this.pageSize = size;
      console.log(this.pageSize)
    },
    // 放大图片
    bigImage (row) {
      this.srcBig = row.VehiclePicPath
      this.showBigDialogVisible = true
    },
    handleClose () {
      this.showBigDialogVisible = false;
    },
    // 限制用户上传的图片格式和大小
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2 
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 上传车辆图片
    afterRead1(file){
       return new Promise((resolve, reject) => {
          // 此时可以自行将文件上传至服务器
          const that = this
          let client = new OSS(this.dataObj)
          const fileName = file.name
          //定义唯一的文件名，打印出来的uid其实就是时间戳
          //client 是第一步中的 client
          client
            .multipartUpload(fileName, file)
            .then((result) => {
              //下面是如果对返回结果再进行处理，根据项目需要
              // console.log(result)
              that.VehicleUrl =
                'http://' +
                result.bucket +
                '.' +
                that.baseAli +
                '/' +
                result.name
              console.log(that.VehicleUrl)
              resolve()
            })
            .catch((err) => {
              console.log('err:', err)
              reject()
            })
        })
    },
    // 上传车本图片
    afterRead2(file){
       return new Promise((resolve, reject) => {
          // 此时可以自行将文件上传至服务器
          const that = this
          let client = new OSS(this.dataObj)
          const fileName = file.name
          //定义唯一的文件名，打印出来的uid其实就是时间戳
          //client 是第一步中的 client
          client
            .multipartUpload(fileName, file)
            .then((result) => {
              //下面是如果对返回结果再进行处理，根据项目需要
              // console.log(result)
              that.CBPicUrl =
                'http://' +
                result.bucket +
                '.' +
                that.baseAli +
                '/' +
                result.name
              console.log(that.CBPicUrl)
              resolve()
            })
            .catch((err) => {
              console.log('err:', err)
              reject()
            })
        })
    },
    afterRead(file) {
        return new Promise((resolve, reject) => {
          // 此时可以自行将文件上传至服务器
          const that = this
          let client = new OSS(this.dataObj)
          const fileName = file.name
          //定义唯一的文件名，打印出来的uid其实就是时间戳
          //client 是第一步中的 client
          client
            .multipartUpload(fileName, file)
            .then((result) => {
              //下面是如果对返回结果再进行处理，根据项目需要
              // console.log(result)
              that.tempUrl =
                'http://' +
                result.bucket +
                '.' +
                that.baseAli +
                '/' +
                result.name
              console.log(that.tempUrl)
              resolve()
            })
            .catch((err) => {
              console.log('err:', err)
              reject()
            })
        })
      },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw)
      }
    }
  }
</script>
<style>
.content {
  overflow-y: scroll;
}
.el-col-6 {
  min-width: 400px;
  min-height: 50px;
}
.el-table th {
  height: 40px;
}
.el-form-item label {
  width: 80px;
}

</style>